<template>
    <div class="fadeInUp animated " style="width: 1200px;margin: 0 auto;height: 140vh; margin-top: 20px ;">
      <template>
        <el-carousel :interval="4000" type="card" height="300px">
          <el-carousel-item v-for="item in slideshow" :key="item.id">
            <a :href="item.a" target="_blank">
              <img style="object-fit: contain;width: 100%" :src="item.src">
            </a>
          </el-carousel-item>
        </el-carousel>
      </template>
      
      <div style="margin: 10px 0">
        <el-row :gutter="10">
          <el-col :span="6" v-for="item in goodsData" :key="item.id" >
            <!-- <div> -->
              <el-card   style="height: 450px; padding: 10px; margin-bottom: 20px; display: flex; flex-direction:column; position: relative; text-align: center;">
              <div @click="toDetails(item.id)" style="">
                <img :src="item.goodsImgUrl" style="width: 85%; height: 200px;">
              </div>
              <div style="  margin-top: 20px; ">
                <i style="">￥</i><span style="color:red; font-size: 25px">{{item.price}}</span>
              </div>
              <div style="height: 70px; padding: 10px 0;overflow: hidden;  ">
                <span class="textname">{{item.name}}</span>
              </div>
              <div style="align-self: flex-end;margin-top: 20px;">
                  <el-button type="danger" style="font-size: 13px" @click="addShoppingTrolley(item)">
                    <i class="el-icon-shopping-cart-2" style="font-size: 18px; padding-right: 5px"></i>加入购物车
                  </el-button>
              </div>
            </el-card>
            <!-- </div> -->
            
          </el-col>
        </el-row>
        <div style="padding: 10px 0; display: flex;justify-content: center;">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pageNum"
              :page-sizes="[20, 30, 40, 50]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
          </el-pagination>
        </div>
      </div>
    </div>
</template>

<script>
export default {
  name: "FrontHome",
  data(){
    return{
      goodsData :[],  //数据
      user : localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")): {},
      total: 0,
      pageNum: 0,
      pageSize: 20,
      slideshow: [
        {
          id:1,
          src: require("../../assets/slideshow_img/jdslideshow1.jpg"),
          a:"https://baike.baidu.com/item/Java/85979?fr=aladdin"
        },
        {
          id:2,
          src: require("../../assets/slideshow_img/jdslideshow2.jpg"),
          a:"https://v2.cn.vuejs.org/"
        },
        {
          id:3,
          src: require("../../assets/slideshow_img/jdslideshow3.jpg"),
          a:"https://element.eleme.cn/#/zh-CN"
        },
        {
          id:4,
          src: require("../../assets/slideshow_img/jdslideshow4.jpg"),
          a:"https://spring.io/"
        },
        {
          id:5,
          src: require("../../assets/slideshow_img/jdslideshow5.jpg"),
          a:"https://nodejs.org/en/"
        },
      ],
    }
  },
  created() {
   this.load();

  this.userShoppingCart();

  //检查用户
    if(this.user.email == null || this.user.address == null|| this.user.avatarUrl == null){
      this.$notify({
        title: '个人中心',
        message: '尊敬的用户您的个人信息尚未完善请移动到个人中心完善个人信息',
        offset: 100,
        type: 'warning',
        duration: 0
      });
    }

    //查看后台图片
    // this.request("/files/front/all").then(res=>{
    //   if(res.code === "200"){
    //     this.files = res.data.filter(v => v.type === "png" ||v.type === "jpg" || v.type === "webp")
    //   }
    // })
  },
  methods:{
    toDetails(id){

      
      this.$router.push(
        {
          path:"/Details/details",
          query:{
            id: id
          }
        }
      );
    },
    load(){
      //查看商品数据
      this.request.get("/goods/front/page",{
        params:{
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name,
        }
      }).then(res => {
        if (res.code === "200") {
          this.goodsData = res.data.data
          this.total = res.data.total
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    //获取后台用户购物车信息
    userShoppingCart(){
      if(this.user.id){
        //查询当前用户购物车
        this.request.get("/shoppingCart/userShoppingAll/"+this.user.id).then(res=>{
          if(res.code === "200"){
            let Goodss =[]
            for (let i = 0; i < res.data.length; i++) {
              Goodss.push(res.data[i].shoppingGoods)
            }
            this.$store.state.shoppingNum = Goodss.length
            this.$store.state.shoppingList  = Goodss;
            console.log("this.$store.state.shoppingList",this.$store.state.shoppingList)
          }else {
            this.$message.error("后台获取购物车数据异常")
          }
        })
      }else {
        this.$message.error("请先登录方可使用购买功能");
      }

    },
    //分页方法
    handleSizeChange(pageSize) {
      this.pageSize=pageSize;
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.load()
    },
    //添加商品
    addShoppingTrolley(item){
      if(this.user.id){
        let flag = false;
        let valitem ;
        this.$store.state.shoppingList.forEach( (val,index)=>{
          if(item.id == val.id){
            this.$store.state.shoppingList[index].quantity++;
            valitem =  this.$store.state.shoppingList[index];
            flag =true;
          }
        })

        if(flag === false){
          this.successShopping();
          this.$store.state.shoppingNum++;
          item.quantity =1;
          //向数据库添加新数据 无id
          let userShopping = {
            userId : this.user.id,
            goods : item.id,
            quantity: item.quantity
          }
          this.request.post("/shoppingCart",userShopping).then(res =>{

            this.userShoppingCart()
          })

          this.$store.state.shoppingList.push(item);


        }else {
          this.repetitionOpen(valitem)
        }

      }else {
        this.$notify({
          title: '请先登录',
          message: '登录后方可加入购物车',
          type: 'warning',
          offset: 100
        });
      }



    },
    successShopping() {
      this.$notify({
        title: '成功添加',
        message: '恭喜你添加了一个商品到购物车',
        type: 'success',
        position: 'bottom-right'
      });
    },
    repetitionOpen(valitem) {
      this.$confirm('购物车已经存在此商品, 是否继续添加?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if( valitem.quantity <=10){
          //改变商品数量
          let userShopping = {
            id: valitem.shoppingId,
            userId : this.user.id,
            goods : valitem.id,
            quantity: valitem.quantity
          }
          this.request.post("/shoppingCart",userShopping).then(res =>{
          })


          this.$notify({
            title: '商品+1',
            message: '恭喜你成功添加到购物车',
            offset: 100,
            type: 'success',
          });
        }else {
          this.$notify.error({
            title: '失败',
            message: '添加失败购物车同类商品最高上限为10',
            offset: 100,
          });
        }


      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消添加'
        });
      });
    }
  }
}
</script>

<style scoped>

.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 200px;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n+1) {
  background-color: #d3dce6;
}
.textname{
  font-size: 13px;
  display:block;
  word-break:keep-all;
  overflow:hidden;
  text-overflow:ellipsis;
  -o-text-overflow:ellipsis;
  -webkit-line-clamp: 3;
  -icab-text-overflow:ellipsis;
  -khtml-text-overflow:ellipsis;
  -moz-text-overflow: ellipsis;
  -webkit-text-overflow:ellipsis;

}

</style>